package csp

import (
	"crypto/x509"
	"encoding/base64"
	"encoding/pem"

	"github.com/pkg/errors"

	hecdsa "nft-server/csp/internal/ecdsa"
)

// VerifySignature to verify the certificate provided by client is signed by the specific CA or not,
// and to verify the signature is valid or not   certificate证书
func VerifySignature(certByte []byte, signedData, data string, caCert []byte) error {
	// cipherText 密码报文
	cipherText, err := base64.URLEncoding.DecodeString(signedData)
	if err != nil {
		return err
	}
	text, err := base64.URLEncoding.DecodeString(data)
	if err != nil {
		return err
	}
	b, _ := pem.Decode(certByte)
	if b == nil {
		return errors.Errorf("certificate invalid")
	}
	cert, err := x509.ParseCertificate(b.Bytes)
	if cert != nil && err == nil && cert.PublicKeyAlgorithm == x509.ECDSA {
		err = hecdsa.Verify(cert, cipherText, text, caCert)
		return err
	}
	return errors.Errorf("VerifySignature unsupported algorithm")
}

func GetOrganizationNameFromCert(certByte []byte) (string, error) {
	b, _ := pem.Decode(certByte)
	if b == nil {
		return "", errors.Errorf("certificate invalid")
	}
	cert, err := x509.ParseCertificate(b.Bytes)
	if cert != nil && err == nil && cert.PublicKeyAlgorithm == x509.ECDSA {
		return cert.Subject.Organization[0], nil
	}
	return "", err
}
